package com.suyundeng.menu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.suyundeng.entity.SMenu;
import com.suyundeng.entity.SRole;
import com.suyundeng.entity.SUser;
import com.suyundeng.menu.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SUser user = userMapper.selectOne(new QueryWrapper<SUser>().lambda().eq(SUser::getUserName,s));
        if (user==null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //将登录成功的用户存入会话中
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        session.setAttribute("user",user);

        //获取权限和角色
        List<SMenu> menus = userMapper.selectMenusByUsername(s);
        List<SRole> roles = userMapper.selectRolesByUserName(s);
        StringBuilder stringBuilder =new StringBuilder();
        menus.forEach(menu -> stringBuilder.append(menu.getMenuName()+","));
        roles.forEach(role -> stringBuilder.append("ROLE_"+role.getRoleName()+","));
        if (stringBuilder.length() > 0){
            stringBuilder.deleteCharAt(stringBuilder.length()-1);
        }

        return new org.springframework.security.core.userdetails.User(
                user.getUserName(), user.getPassWord(),
                AuthorityUtils.commaSeparatedStringToAuthorityList(stringBuilder.toString())
        );
    }
}
